﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Xinchen.SOA.Client;

namespace Xinchen.SOA.TestApplication.Testers
{

    public abstract class TesterBase
    {

        #region 公用
        static IList<TesterBase> _testers = new List<TesterBase>();
        public static IList<TesterBase> GetAllTester()
        {
            if (_testers.Count > 0)
            {
                return _testers;
            }
            var allTypes = Assembly.GetExecutingAssembly().GetTypes().Where(x => typeof(TesterBase).IsAssignableFrom(x) && x.FullName != "Xinchen.SOA.TestApplication.Testers.TesterBase");
            foreach (var item in allTypes)
            {
                _testers.Add((TesterBase)Activator.CreateInstance(item));
            }
            return _testers;
        }

        protected TResponse SendRequest<TResponse>(string url, object request, string token)
        {
            HttpClient client = new HttpClient();
            using (client)
            {
                client.DefaultRequestHeaders.Add("ApplicationId", ConfigurationManager.AppSettings["applicationId"]);
                client.DefaultRequestHeaders.Add("ApplicationKey", ConfigurationManager.AppSettings["applicationKey"]);
                var response = client.PostAsync(url, request, new JsonMediaTypeFormatter()).Result;
                var result = response.Content.ReadAsStringAsync().Result;
                try
                {
                    response.EnsureSuccessStatusCode();
                }
                catch (Exception e)
                {
                    throw new Exception(result);
                }
                return response.Content.ReadAsAsync<TResponse>(new MediaTypeFormatter[] { new JsonMediaTypeFormatter() }).Result;
            }
        }
        #endregion

        public abstract UserControl ParameterForm { get; }

        protected string BuildUrl(string api)
        {
            return ConfigurationManager.AppSettings["gateway"] + "tradeforappapi/withdrawalservice/" + api;
        }
        public event Action<string> OnShowMessage;
        public void ShowMessage(string log)
        {
            if (OnShowMessage == null) return;
            OnShowMessage(log);
        }
        public abstract string Name { get; }
        public abstract object Test(string token);

        public static Form ActiveForm { get; set; }
    }
}
